import { createRouter, createWebHashHistory } from "vue-router";
import { getRoutesList } from "@/request/api";
// import HomeView from "@/views/HomeView.vue";
// 首屏懒加载
const HomeView = () => import("@/views/HomeView.vue");
interface RouteMeta {
  title: string;
}

interface RouteConfig {
  name: string;
  path: string;
  menuId: number | string;
  parentId: number | string;
  meta: RouteMeta;
  component: () => Promise<any>;
  children?: RouteConfig[];
}

let allRoutes: any = [];

// 获取动态路由配置

try {
  const response = await getRoutesList();
  function formatPath(path: string): string {
    // 如果路径不以 '/' 开头，则在前面加上 '/'
    if (!path.startsWith("/")) {
      path = "/" + path;
    }
    return `../views${path}.vue`;
  }
  allRoutes = response.data.list.map((item: RouteConfig) => ({
    name: item.name,
    menuId: item.menuId,
    // 判断当路由出问题时
    path: item.path.startsWith("/") ? item.path : "/" + item.path,
    meta: item.meta,
    component: HomeView,
    children: item.children
      ? item.children.map((child: any) => ({
          parentId: child.parentId,
          name: child.name,
          path: child.path.startsWith("/") ? child.path : "/" + child.path,
          meta: child.meta,
          menuId: child.menuId,
          component: () => import(/* @vite-ignore */ formatPath(child.path)),
        }))
      : [],
  }));
} catch (error) {
  console.error("获取路由列表失败:", error);
  allRoutes = [
    {
      name: "HomeView",
      path: "/HomeView",
      meta: {
        title: "首页",
      },
      component: () => import("@/views/HomeView.vue"),
    },
    {
      name: "login",
      path: "/",
      meta: {
        title: "登录页",
      },
      component: () => import("@/components/login/login.vue"),
    },
  ];
}
let routes = [
  {
    name: "HomeView",
    path: "/HomeView",
    meta: {
      title: "首页",
    },
    component: () => import("@/views/HomeView.vue"),
  },
  {
    name: "login",
    path: "/",
    meta: {
      title: "登录页",
    },
    component: () => import("@/components/login/login.vue"),
  },
  {
    name: "404",
    path: "/:pathMatch(.*)*", // 捕获所有路径的路由
    meta: {
      hidden: true,
    },
    component: () => import("@/components/error/error.vue"),
  },
];
// 路由数组合并
routes = [...routes, ...allRoutes];
// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
// 路由守卫
router.afterEach((to) => {
  if (to.meta.title) {
    document.title = to.meta.title as string;
  }
});
export default router;
